import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.font_manager import FontProperties

font_path = "./results/宋体.ttf"
font = FontProperties(fname=font_path, size=30)


def show(y):
    # 参数为一个list
    len_y = len(y)
    x = range(2000, 2000 + len_y)
    _y = [y[-1]] * len_y

    fig = plt.figure(figsize=(960 / 72, 360 / 72))
    ax1 = fig.add_subplot(1, 1, 1)

    ax1.plot(x, y, color='blue')
    plt.xlabel("年", fontproperties=font)
    plt.ylabel("元", fontproperties=font)
    plt.xlim(2000, 2031)
    line_x = ax1.plot(x, _y, color='skyblue')[0]
    line_y = ax1.axvline(x=2000 + len_y - 1, color='skyblue')

    ax1.set_title('2000年以来中国油价走势', fontproperties=font)
    # 标签
    text0 = plt.text(len_y - 1, y[-1], str(y[-1]), fontsize=10)

    def scroll(event):
        axtemp = event.inaxes
        x_min, x_max = 2000, 2032
        fanwei_x = (x_max - x_min) / 10
        if event.button == 'up':
            axtemp.set(xlim=(x_min + fanwei_x, x_max - fanwei_x))
        elif event.button == 'down':
            axtemp.set(xlim=(x_min - fanwei_x, x_max + fanwei_x))
        fig.canvas.draw_idle()

    # 这个函数实时更新图片的显示内容
    def motion(event):
        try:
            temp = y[int(np.round(event.xdata)) - 2000]
            for i in range(len_y):
                _y[i] = temp
            line_x.set_ydata(_y)
            line_y.set_xdata(event.xdata)
            ######
            text0.set_position((event.xdata, temp))
            text0.set_text(str(temp))
            fig.canvas.draw_idle()  # 绘图动作实时反映在图像上
        except:
            pass

    fig.canvas.mpl_connect('scroll_event', scroll)
    fig.canvas.mpl_connect('motion_notify_event', motion)
    plt.show()


dataf = pd.read_csv('./results/中国油价/pred_results.csv')
dataf1 = list(dataf['date'])
dataf = list(dataf['中国油价'])

plt.ion()
for i in range(1, len(dataf)):
    plt.cla()
    plt.title("2000年以来中国油价走势", fontproperties=font)
    plt.plot(dataf1[:i], dataf[:i])
    plt.xlabel("年", fontproperties=font)
    plt.ylabel("元", fontproperties=font)
    plt.pause(0.25)
plt.ioff()
plt.close()
show(dataf)
